using System.Reflection;
using SqlSugar;

namespace Gateway.SqlSugar.Splits;

public class SplitTableService : ISplitTableService
{
    /// <summary>
    /// 返回数据库中所有分表
    /// </summary>
    /// <param name="db"></param>
    /// <param name="EntityInfo"></param>
    /// <param name="tableInfos"></param>
    /// <returns></returns>
    public List<SplitTableInfo> GetAllTables(ISqlSugarClient db, EntityInfo EntityInfo, List<DbTableInfo> tableInfos)
    {
        List<SplitTableInfo> result = new List<SplitTableInfo>();
        foreach (var item in tableInfos)
        {
            if (item.Name.Contains("_")) //区分标识如果不用正则符复杂一些，防止找错表
            {
                SplitTableInfo data = new SplitTableInfo()
                {
                    TableName = item.Name //要用item.name不要写错了
                };
                result.Add(data);
            }
        }

        return result.OrderBy(it => it.TableName).ToList(); // 打断点看一下有没有查出所有分表
    }

    /// <summary>
    /// 默认表名
    /// </summary>
    /// <param name="db"></param>
    /// <param name="EntityInfo"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public string GetTableName(ISqlSugarClient db, EntityInfo EntityInfo)
    {
        return EntityInfo.DbTableName + "_00";
    }

    public string GetTableName(ISqlSugarClient db, EntityInfo EntityInfo, SplitType type)
    {
        return EntityInfo.DbTableName + "_00";
    }

    public string GetTableName(ISqlSugarClient db, EntityInfo entityInfo, SplitType splitType, object fieldValue)
    {
        if (fieldValue == null)
        {
            return entityInfo.DbTableName + "_00";
        }

        if (fieldValue.GetType() == typeof(string))
        {
            return entityInfo.DbTableName + "_" + SplitTableExtension.GetTableNameSuffix(fieldValue);
        }

        return entityInfo.DbTableName + "_00";
    }

    /// <summary>
    /// 获取分表字段的值
    /// </summary>
    /// <param name="db"></param>
    /// <param name="entityInfo"></param>
    /// <param name="splitType"></param>
    /// <param name="entityValue"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public object GetFieldValue(ISqlSugarClient db, EntityInfo entityInfo, SplitType splitType, object entityValue)
    {
        var splitColumn =
            entityInfo.Columns.FirstOrDefault(it => it.PropertyInfo.GetCustomAttribute<SplitFieldAttribute>() != null);
        return splitColumn?.PropertyInfo.GetValue(entityValue, null);
    }
}